package com.usts2022.classcostrecord;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.usts2022.classcostrecord.Utils.DateFormat;
import com.usts2022.classcostrecord.Utils.HttpUtils;
import com.usts2022.classcostrecord.entity.Question;
import com.usts2022.classcostrecord.entity.Report;
import com.usts2022.classcostrecord.entity.User;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class QuestionFragment extends Fragment {

    private RecyclerView recycleView;
    private OrderListAdapter mAdapter;

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private User mUser;
    private Report mReport;
    private List<Question> questionList;

    public static QuestionFragment newInstance(User user, Report report) {
        QuestionFragment fragment = new QuestionFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, user);
        args.putSerializable(ARG_PARAM2, report);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden == false) {
            try {
                getQuestion(mReport.getId());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mUser = (User) getArguments().getSerializable(ARG_PARAM1);
            mReport = (Report) getArguments().getSerializable(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_question, container, false);
        recycleView = view.findViewById(R.id.recycle_question);
        recycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        try {
            getQuestion(mReport.getId());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return view;
    }


    //adapter
    class OrderListAdapter extends RecyclerView.Adapter<OrderHolder> {

        @NonNull
        @Override
        public OrderHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            return new OrderHolder(layoutInflater, parent);
        }

        @Override
        public void onBindViewHolder(@NonNull OrderHolder holder, int position) {
            Question question = questionList.get(position);
            holder.setIsRecyclable(false);
            holder.bind(question);
        }

        @Override
        public int getItemCount() {
            if (questionList == null) {
                return 0;
            }
            return questionList.size();
        }
    }

    class OrderHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView confirmStatus;
        private TextView content;
        private TextView confirmNumber;
        private Question mQuestion;

        public OrderHolder(LayoutInflater inflater, ViewGroup parent) {
            super(inflater.inflate(R.layout.list_question, parent, false));
            itemView.setOnClickListener(this);
            //绑定
            content = itemView.findViewById(R.id.question_content);
            confirmNumber = itemView.findViewById(R.id.confirm_number);
            confirmStatus = itemView.findViewById(R.id.confirm_status);
        }

        public void bind(Question question) {
            mQuestion = question;
            content.setText(mQuestion.getContent());
            new Thread() {
                @Override
                public void run() {
                    String url1 = "/user/checkQuestionNumber/" + question.getId();
                    String url2 = "/user/getClassNumber/" + mUser.getClassCode();
                    try {
                        Response res1 = HttpUtils.getNoTh(url1);
                        Response res2 = HttpUtils.getNoTh(url2);
                        int questionNumber = Integer.parseInt(res1.body().string());
                        int classNumber = Integer.parseInt(res2.body().string());
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                confirmNumber.setText("质疑确认人数: " + questionNumber + "/" + classNumber);
                                if (questionNumber>classNumber/2) {
                                    confirmStatus.setText("已确认");
                                }
                            }
                        });

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }


        //点击事件
        @Override
        public void onClick(View view) {
            FragmentManager fm = getActivity().getSupportFragmentManager();
            AnswerFragment answerFragment = AnswerFragment.newInstance(mQuestion,mUser);
            fm.beginTransaction().hide(QuestionFragment.this).add(R.id.constraintLayout3,answerFragment).addToBackStack(null).commitAllowingStateLoss();
        }
    }

    private void getQuestion(long reportId) throws IOException {
        String url = "/user/findAllQuestion/" + reportId;
        HttpUtils.get(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();
                String str = response.body().string();
                if (response.code() != 200 || str.equals("")) {
                    Toast.makeText(getActivity(), "获取数据失败", Toast.LENGTH_SHORT).show();
                } else {
                    questionList = JSON.parseArray(str, Question.class);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter = new OrderListAdapter();
                            recycleView.setAdapter(mAdapter);
                        }
                    });
                }
                Looper.loop();
            }
        });
    }
}